/*
 * Aboboo Android
 * Copyright (C) 2012 www.aboboo.com
 * 
 */
package com.aboboo.android.player;

import java.util.Timer;
import java.util.TimerTask;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 
 * @author fangpeng
 * 
 * @version 1.0 2013-01-31
 * 
 */
public class SafetyTimer {
	private Timer mTimer = null;
	private Handler mHandler = null;
	private TimerTask mTask = null;
	private OnTimeListener mListener = null;
	private long mInterval = 0; // in milliseconds
	private static final String TAG = new String("SafetyTimer");

	// Observer接口定义
	public interface OnTimeListener {
		public void OnTimer();
	}

	// 创建定时器并指定Observer
	public SafetyTimer(long interval, OnTimeListener listener) {
		mInterval = interval;
		mListener = listener;
	}

	// 启动定时器
	public void startTimer() {
		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (mListener != null) {
					mListener.OnTimer();
					Log.i(TAG, "mListener.OnTimer()");
				}
				super.handleMessage(msg);
			}
		};
		mTask = new TimerTask() {
			public void run() {
				Message message = new Message();
				message.what = 0; // anything is ok.
				mHandler.sendMessage(message);
			}
		};
		mTimer = new Timer();
		mTimer.schedule(mTask, 0, mInterval);
	}

	// 停止Timer动作
	// 释放获得的资源。
	public void stopTimer() {
		mTimer.cancel();
		mTimer.purge();
		mTimer = null;
		mHandler = null;
		mTask = null;
		Log.i(TAG, "stopTimer()");
	}

	// Timer是否处于工作状态。
	public boolean isRunging() {
		return (mTimer != null);
	}
}
